/**
 * 订单信息表实现类
 */
package com.bys.ots.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;


import com.alibaba.fastjson.JSON;
import com.bys.ots.dao.EmailMapper;
import com.bys.ots.dao.SoDnInfoMapper;
import com.bys.ots.model.*;
import com.bys.ots.service.ISoInfoService;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import nu.xom.ParsingException;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bys.ots.dao.SoInfoMapper;
import com.bys.ots.pojo.ConstantModel;
import com.bys.ots.pojo.Result;
import com.bys.ots.pojo.ResultEnum;
import com.bys.ots.pojo.ResultUtil;
import com.bys.ots.util.LogisticUtil;
import org.springframework.util.ObjectUtils;

/**
 * @author bairuihua
 * 2019/11/26
 */
@Service(value = "soInfoService")
public class SoInfoServiceImpl implements ISoInfoService {
    private final Logger logger = LoggerFactory.getLogger(SoInfoServiceImpl.class);

    @Resource
    private SoInfoMapper soInfoMapper;

    @Resource
    private SoDnInfoMapper soDnInfoMapper;

    @Autowired
    ConstantModel constantModel;

    @Resource
    private EmailMapper emailMapper;

    public List<VSoInfo> getVSoInfoList(String so,String email){
        List<VSoInfo>soInfoList = soInfoMapper.selectBySoAndEmail( so,email);
        return  soInfoList;
    }
    public Result getSoInfoList(String rawData) {
        if (StringUtils.isEmpty(rawData)) {
            logger.error("->rawData empty  error, the request info is：rawData:{}", rawData);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        //Ship-to-code，Ship-to-name，bill-to-code，bill-to-name, Sale Email，CSR Email，SKU number，SKU name，so
        JSONObject jsonObj = JSONObject.parseObject(rawData);
        String userId = jsonObj.getString("userId");
        String deliveryStatus = jsonObj.getString("deliveryStatus");
        String pageNum = jsonObj.getString("pageNum");
        String pageSize = jsonObj.getString("pageSize");
        //searchType：“shipToCode”，secarchContent：“5555”
        String searchType = jsonObj.getString("searchType");
        String searchContent = jsonObj.getString("secarchContent");
        String so = jsonObj.getString("so");
        String choice = jsonObj.getString("choice");
        String startDate = jsonObj.getString("startDate");
        String endDate = jsonObj.getString("endDate");
        String shipToCode = jsonObj.getString("shipToCode");
        String shipToName = jsonObj.getString("shipToName");
        String billToCode = jsonObj.getString("billToCode");
        String billToName = jsonObj.getString("billToName");
        String saleEmail = jsonObj.getString("saleEmail");
        String csrEmail = jsonObj.getString("csrEmail");
        String skuNumber = jsonObj.getString("skuNumber");
        String skuName = jsonObj.getString("skuName");
        String poNumber = jsonObj.getString("poNumber");
        if (StringUtils.isEmpty(searchType)) {
            if (StringUtils.isNotEmpty(searchContent)) {
                so = searchContent;
            }
        }
        if (StringUtils.isNotEmpty(searchType)) {
            if (StringUtils.equals("so", searchType)) {
                so = searchContent;

            }
            if (StringUtils.equals("choice", searchType)) {
                choice = searchContent;
            }
            if (StringUtils.equals("startDate", searchType)) {
                startDate = searchContent;
            }
            if (StringUtils.equals("endDate", searchType)) {
                endDate = searchContent;
            }
            if (StringUtils.equals("shipToCode", searchType)) {
                shipToCode = searchContent;
            }
            if (StringUtils.equals("shipToName", searchType)) {
                shipToName = searchContent;
            }
            if (StringUtils.equals("billToCode", searchType)) {
                billToCode = searchContent;
            }
            if (StringUtils.equals("billToName", searchType)) {
                billToName = searchContent;
            }
            if (StringUtils.equals("saleEmail", searchType)) {
                saleEmail = searchContent;
            }
            if (StringUtils.equals("csrEmail", searchType)) {
                csrEmail = searchContent;
            }
            if (StringUtils.equals("skuNumber", searchType)) {
                skuNumber = searchContent;
            }
            if (StringUtils.equals("skuName", searchType)) {
                skuName = searchContent;
            }
            if (StringUtils.equals("poNumber", searchType)) {
                poNumber = searchContent;
            }
        }

        if (StringUtils.isEmpty(userId)) {
            logger.error("-> rawData解析后的 userId为空 => userId:{}", userId);
            return ResultUtil.error(ResultEnum.CODE_410);
        }
        if (StringUtils.isEmpty(so)) {
            so = null;
        }
        if (StringUtils.isEmpty(deliveryStatus)) {
            deliveryStatus = null;
        }
        if (StringUtils.isEmpty(choice)) {
            choice = null;
        }
        if (StringUtils.isEmpty(startDate)) {
            startDate = null;
        }
        if (StringUtils.isEmpty(endDate)) {
            endDate = null;
        }

        if (StringUtils.isEmpty(shipToCode)) {
            shipToCode = null;
        }
        if (StringUtils.isEmpty(shipToName)) {
            shipToName = null;
        }
        if (StringUtils.isEmpty(billToCode)) {
            billToCode = null;
        }
        if (StringUtils.isEmpty(billToName)) {
            billToName = null;
        }
        if (StringUtils.isEmpty(saleEmail)) {
            saleEmail = null;
        }
        if (StringUtils.isEmpty(csrEmail)) {
            csrEmail = null;
        }
        if (StringUtils.isEmpty(skuNumber)) {
            skuNumber = null;
        }
        if (StringUtils.isEmpty(skuName)) {
            skuName = null;
        }
        if (StringUtils.isEmpty(poNumber)) {
            poNumber = null;
        }
        int startOff = 0;
        startOff = (Integer.parseInt(pageNum) - 1) * Integer.parseInt(pageSize);
        List<SoInfo> soInfoList = null;
        List<Email> emailList = emailMapper.findByUserId(userId);
        Boolean bool = false;
        for (Email email : emailList) {
            if (StringUtils
                    .equalsIgnoreCase("LSGCNreagentcs@thermofisher.onmicrosoft.com", email.getEmail()) ||
                    StringUtils.equalsIgnoreCase("CSSH@thermofisher.com", email.getEmail()) ||
                    StringUtils.equalsIgnoreCase("byron.shi@thermofisher.com", email.getEmail())) {
                bool = true;
            }
        }
        List soList = new ArrayList();
        if (StringUtils.isNotEmpty(so)) {
            so = so.replaceAll("，", ",");
            String[] soArray = so.split(",");
            for (String item : soArray) {
                soList.add(item);
            }
        }

        if (bool) {
            soInfoList = soInfoMapper.selectByStatus(deliveryStatus, soList, shipToCode,
                    shipToName,
                    billToCode,
                    billToName,
                    saleEmail,
                    csrEmail,
                    skuNumber,
                    skuName, choice,
                    poNumber,
                    startDate, endDate, startOff,
                    Integer.parseInt(pageSize));
        } else {
            soInfoList = soInfoMapper.selectByEmailAndStatus(userId, deliveryStatus, soList, shipToCode,
                    shipToName,
                    billToCode,
                    billToName,
                    saleEmail,
                    csrEmail,
                    skuNumber,
                    skuName, choice,
                    poNumber,
                    startDate, endDate, startOff,
                    Integer.parseInt(pageSize));


        }
//        if (ObjectUtils.isEmpty(soInfoList)) {
//            soInfoList = soInfoMapper.selectByEmailAndStatus("07f84ffd-1c7b-4b93-8cf7-c0d4c7b4fc4a", deliveryStatus, soList, shipToCode,
//                    shipToName,
//                    billToCode,
//                    billToName,
//                    saleEmail,
//                    csrEmail,
//                    skuNumber,
//                    skuName, choice, startDate, endDate, startOff,
//                    Integer.parseInt(pageSize));
//        }
        clearnDirty(soInfoList);
        //sap的数据  A：未发货 B：部分发货   C：完全发货
        logger.info("->查找到的订单数量为：" + soInfoList.size());
        return ResultUtil.OTSResult(soInfoList);
    }

    List<SoInfo> adapterE1List(List<SoInfo> soInfoListE1, String deliveryStatus) {
        //分组
        Map<String, List<SoInfo>> groupSoInfoList = soInfoListE1.stream()
                .collect(Collectors.groupingBy(SoInfo::getSo));
        //去重
        Map<String, SoInfo> soInfoListMap = soInfoListE1.stream().collect(
                Collectors.toMap(SoInfo::getSo, a -> a, (k1, k2) -> k1));
        List<SoInfo> listE1 = new ArrayList();
        for (Map.Entry<String, SoInfo> entry : soInfoListMap.entrySet()) {
            List<SoInfo> listSoInfo = groupSoInfoList.get(entry.getKey());
            String status = getStatus(listSoInfo);
            if (null == deliveryStatus) {
                entry.getValue().setDeliveryStatus(status);
                listE1.add(entry.getValue());
            } else {
                if (StringUtils.equals(deliveryStatus, status)) {
                    entry.getValue().setDeliveryStatus(status);
                    listE1.add(entry.getValue());
                }
            }
        }
        return listE1;
    }

    public String getStatus(List<SoInfo> listSoInfo) {
        int num = 0;
        int count = listSoInfo.size();
        for (SoInfo soinfo : listSoInfo) {
            String billingStatus = soinfo.getBillingStatus();
            if (StringUtils.equals("已发货", billingStatus) ||
                    StringUtils.equals("已发货（直发）", billingStatus) ||
                    StringUtils.equals("已发货(直发)", billingStatus)) {
                num += 1;
            }
        }
        if (num == 0) {
            return "A";
        }
        if (num == count) {
            return "C";
        }
        return "B";
    }

    public List<SoInfo> clearnDirty(List<SoInfo> soInfoList) {
        for (SoInfo soInfo : soInfoList) {
            if (ObjectUtils.isEmpty(soInfo) || StringUtils.isEmpty(soInfo.getType())) {
                continue;
            }
            if (StringUtils.equals("e1", soInfo.getType())) {
                if (!StringUtils.isEmpty(soInfo.getShipToName())) {
                    String regex = "\\（.*?\\）|\\(.*?\\)";
                    soInfo.setShipToName(soInfo.getShipToName().replaceAll(regex, ""));
                }
                if (!StringUtils.isEmpty(soInfo.getSoldToName())) {
                    String regex = "\\（.*?\\）|\\(.*?\\)";
                    soInfo.setSoldToName(soInfo.getSoldToName().replaceAll(regex, ""));
                }
            }

        }
        return soInfoList;
    }


    public SoInfo clearnDirty(SoInfo soInfo) {
        List<SoInfo> soInfoList = new ArrayList();
        soInfoList.add(soInfo);
        return clearnDirty(soInfoList).get(0);
    }

    public Result getSoInfoDetail(String userId, String so, String type) {

        if (StringUtils.isEmpty(userId)) {
            logger.error("->orderId is empty, the request is: userId：{}",
                    userId);
            return ResultUtil.error(ResultEnum.CODE_410);
        }
        if (StringUtils.isEmpty(so)) {
            logger.error("->so is empty, the request is: so：{}",
                    so);
            return ResultUtil.error(ResultEnum.CODE_406);
        }
        if (StringUtils.isEmpty(type)) {
            logger.error("->type is empty, the request is: type：{}",
                    type);
            return ResultUtil.error(ResultEnum.CODE_416);
        }

        if (StringUtils.equals(type.toUpperCase(), "SAP")) {
            return getSoInfoDetail(so, 0);
        } else if (StringUtils.equals(type.toUpperCase(), "E1")) {
            return getSoInfoDetail(so, 1);

        } else {
            return ResultUtil.error(ResultEnum.CODE_416);
        }
    }

    public List<Map> getSaleList(SoInfo soInfo, List<SoInfo> soInfoList) {
        List list = new ArrayList();
        if (StringUtils.equals("e1", soInfo.getType())) {
            for (SoInfo each : soInfoList) {
                Map map = new HashMap();
                map.put("salePersonEmail", each.getSalePersonEmail());
                map.put("salePersonName", each.getSalePersonName());
                map.put("salePersonPhone", each.getSalePersonPhone());
                list.add(map);
            }
        }
        if (StringUtils.equals("sap", soInfo.getType())) {
            for (SoInfo each : soInfoList) {
                if (StringUtils.equals("1", each.getPersonType())) {
                    Map map = new HashMap();
                    map.put("salePersonName", each.getSalePersonName());
                    map.put("salePersonEmail", each.getSalePersonEmail());

                    map.put("salePersonPhone", each.getSalePersonPhone());
                    list.add(map);
                }
            }
        }
        return list;
    }

    public List<Map> getCsrList(SoInfo soInfo, List<SoInfo> soInfoList) {
        List csrlist = new ArrayList();
        if (StringUtils.equals("e1", soInfo.getType())) {
            if (StringUtils.equals("CC", soInfo.getSoType())) {
                Map map = new HashMap();
                map.put("csrPhone", "8008208982(座机) & 4008208982(手机)");
                map.put("csrEmail", "CSSH@thermofisher.com");
                csrlist.add(map);
            }
            if (!StringUtils.equals("CC", soInfo.getSoType()) && !StringUtils.equals("CB", soInfo.getSoType())) {
                Map map = new HashMap();
                map.put("csrPhone", "8008208982(座机) & 4008208982(手机)");
                map.put("csrEmail", "LSGCNreagentcs@thermofisher.onmicrosoft.com");
                csrlist.add(map);
            }
        }
        if (StringUtils.equals("sap", soInfo.getType())) {
            for (SoInfo each : soInfoList) {
                if (StringUtils.equals("2", each.getPersonType())) {
                    Map map = new HashMap();
                    map.put("csrEmail", each.getSalePersonEmail());
                    map.put("csrPhone", each.getSalePersonPhone());
                    csrlist.add(map);
                }
            }
        }
        return csrlist;
    }

    private List<SoInfoItem> transSoInfoItem2(List<SoInfoItem> dns) {
        for (SoInfoItem soInfoItem : dns) {
            if (StringUtils.equals("e1", soInfoItem.getType())) {
                if (StringUtils.isNotEmpty(soInfoItem.getKitIdentify()) && !StringUtils.equals(soInfoItem.getKitIdentify(), soInfoItem.getSoItem())) {
                    soInfoItem.setKitType("0");
                    continue;
                }
                int i = 0;
                for (SoInfoItem soInfoItem1 : dns) {

                    if (StringUtils.equals(soInfoItem.getSo(), soInfoItem1.getSo())) {

                        if (StringUtils.equals(soInfoItem.getKitIdentify(), soInfoItem1.getKitIdentify())) {
                            i++;
                            if (i >= 2) {
                                break;
                            }
                        }
                    }

                }
                if (i >= 2) {
                    soInfoItem.setKitType("1");
                }
            }
        }
        return dns;
    }

    private List<SoInfoItem> transSoInfoItem(List<SoInfoItem> dns) {
        List<SoInfoItem> dnsPart = new ArrayList();
        for (SoInfoItem soInfoItem : dns) {
            if (StringUtils.equals("e1", soInfoItem.getType())) {
                if (StringUtils.isNotEmpty(soInfoItem.getKitIdentify()) && !StringUtils.equals(soInfoItem.getKitIdentify(), soInfoItem.getSoItem())) {
                    soInfoItem.setKitType("0");
                    soInfoItem.setSoInfoItemList(null);
                } else {
                    dnsPart.add(soInfoItem);
                }
                if (StringUtils.equals("0", soInfoItem.getKitType())) {
                    for (SoInfoItem soInfoItem1 : dnsPart) {
                        if (StringUtils.equals(soInfoItem.getSo(), soInfoItem1.getSo())) {
                            if (StringUtils.equals(soInfoItem.getKitIdentify(), soInfoItem1.getSoItem())) {
                                soInfoItem1.getSoInfoItemList().add(soInfoItem);
                                soInfoItem1.setKitType("1");
                            }
                        }
                    }
                }
            }
        }

        return dnsPart;
    }

    public Result getSoInfoDetail(String SO, int type) {
        Map<String, Object> result = new HashMap<String, Object>();
        List<SoInfo> soInfoList = soInfoMapper.selectBySO(SO, type);
        SoInfo soInfo = null;
        soInfo = soInfoList.get(0);
        if (!ObjectUtils.isEmpty(soInfo)) {
            soInfo = clearnDirty(soInfo);
        }
        List list = getSaleList(soInfo, soInfoList);
        List csrList = getCsrList(soInfo, soInfoList);
        soInfo.setSaleList(list);
        soInfo.setCsrList(csrList);
        List<SoInfoItem> dns = soDnInfoMapper.selectBySO(SO);
        List<SoInfoItem> dnsPart = null;
        if (StringUtils.equals("e1", soInfo.getType())) {
            dnsPart = transSoInfoItem(dns);
        }
        if (StringUtils.equals("sap", soInfo.getType())) {
            dnsPart = dns;
        }

        result.put("orderDetail", soInfo);
        result.put("DnDetail", dnsPart);
        return ResultUtil.OTSResult(result);
    }

    public Result getLogisticInfo(String type, String so, String soItem) {
        if (StringUtils.isEmpty(type)) {
            logger.error("->orderId is empty, the request is: type：{}",
                    type);
            return ResultUtil.error(ResultEnum.CODE_416);
        }

        if (StringUtils.isEmpty(so)) {
            logger.error("->type is empty, the request is: so：{}",
                    so);
            return ResultUtil.error(ResultEnum.CODE_406);
        }
        if (StringUtils.isEmpty(soItem)) {
            logger.error("->soItem is empty, the request is: soItem：{}",
                    soItem);
            return ResultUtil.error(ResultEnum.CODE_418);
        }
        if ("SAP".contentEquals(type.toUpperCase())) {
            return getLogisticInfo(so, soItem);
        }
        if ("E1".contentEquals(type.toUpperCase())) {
            return getLogisticInfo(so, soItem);
        }
        return ResultUtil.error(ResultEnum.CODE_416);
    }

    public Result getLogisticInfo(String so, String soItem) {
        DnInfoSap DN = soDnInfoMapper.selectBySOAndItem(so, soItem);
        Map logisticResult = null;
        JSONArray responce2 = null;
        if (null == DN || StringUtils.isEmpty(DN.getDn())||StringUtils.equals("0",DN.getDn())) {
            logisticResult = null;
        } else {
            logisticResult = getLogisticDetail("DN", DN.getDn());
        }

        if (null == logisticResult) {
            return ResultUtil.OTSResult(new ArrayList());
        } else {
            net.sf.json.JSONArray response = net.sf.json.JSONArray.fromObject(logisticResult.get("data"));
            if (response.size() == 0) {
                return ResultUtil.OTSResult(new ArrayList());
            }
            responce2 = getSoInfoByResponce(response);
        }

        return ResultUtil.OTSResult(responce2);
    }

    public Result getSoLogisticInfo(String type, String so) {
        Map logisticResult = null;
        JSONArray responce2 = null;
        if ("SAP".contentEquals(type.toUpperCase())) {
            logisticResult = getLogisticDetail("SO", so);
        } else if ("E1".contentEquals(type.toUpperCase())) {
            logisticResult = getLogisticDetail("SO", so);
        } else {
            return ResultUtil.error(ResultEnum.CODE_416);
        }
        if (ObjectUtils.isEmpty(logisticResult)) {
            return ResultUtil.OTSResult(new ArrayList());
        } else {
            net.sf.json.JSONArray response = net.sf.json.JSONArray.fromObject(logisticResult.get("data"));
            if (response.size() == 0) {
                return ResultUtil.OTSResult(new ArrayList());
            }
            responce2 = getSoInfoByResponce(response);
        }

        return ResultUtil.OTSResult(responce2);

    }

    public JSONArray getSoInfoByResponce(JSONArray response) {
        JSONArray response2 = new JSONArray();
        for (Object obj : response) {
            JSONObject jsonObject = JSON.parseObject(obj.toString());
            if (!ObjectUtils.isEmpty(jsonObject.get("shipmentid"))) {
                String shipmentid = jsonObject.get("shipmentid").toString();
                if (StringUtils.isNotEmpty(shipmentid)) {
                    List<SoInfoItem> soInfo = soDnInfoMapper.selectSoInfoByDN(shipmentid);
                    if (!ObjectUtils.isEmpty(soInfo)) {
                        if (StringUtils.equals("E1", soInfo.get(0).getType().toUpperCase())) {
                            soInfo = transSoInfoItem2(soInfo);
                        }
                    }
                    jsonObject.put("soInfo", soInfo);
                    response2.add(jsonObject);
                }
            }
        }
        return response2;
    }

    public Map getLogisticDetail(String type, String so) {
        Map logisticResult = null;
        try {
            logisticResult = LogisticUtil
                    .searchLogistic(type, so, constantModel.getBuleBoxPartnered());
        } catch (Exception e) {
            logger.error("->获取物流信息失败！ error, the requeset param is:so：{}",
                    so);
        }
        Object obj = null;
        if (!ObjectUtils.isEmpty(logisticResult)) {
            obj = logisticResult.get("data");
            if (!ObjectUtils.isEmpty(obj)) {
                if (!ObjectUtils.isEmpty(obj)) {
                    obj = obj.toString().replaceAll("http://tf-pod.vipservice.tech", "https://tf-pod.oss-cn-beijing.aliyuncs.com");
                }
            }
            logisticResult.put("data", obj);
            return logisticResult;
        } else {
            return null;
        }
    }
}

